package controllers;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Barang;
import system.Controller;
import models.Pesanan;
import models.PesananItem;
import models.Profil;
import models.User;
import system.MailServer;

/**
 * Pesanan Controller
 * 
 * @author Rezan Achmad
 */
@WebServlet(name = "PesananController", urlPatterns = {"/pesanan/index", "/pesanan/history", "/pesanan/confirm", "/pesanan/arrived", "/pesanan/cetakNota"})
public class PesananController extends Controller {

    @Override
    protected void initRules() {
        // Non Guest
        rules.put("/pesanan/index", !identity.isGuest());
        rules.put("/pesanan/history", !identity.isGuest());
        rules.put("/pesanan/confirm", !identity.isGuest());
        rules.put("/pesanan/arrived", !identity.isGuest());
        rules.put("/pesanan/cetakNota", !identity.isGuest());
    }

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();

        if (userPath.equals("/pesanan/index")) {
            actionIndex(request, response);
        } else if (userPath.equals("/pesanan/history")) {
            actionHistory(request, response);
        } else if (userPath.equals("/pesanan/confirm")) {
            actionConfirm(request, response);
        } else if (userPath.equals("/pesanan/arrived")) {
            actionArrived(request, response);
        } else if (userPath.equals("/pesanan/cetakNota")) {
            actionCetakNota(request, response);
        }
    }

    private void actionIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = (String) request.getSession().getAttribute("email");
        if (email != null) {
            User user = (User) User.getByEmail(email);
            if (user != null) {
                ArrayList<Pesanan> listPesanan = Pesanan.getInstance().getAllPesananMenunggu(user.id);
                request.setAttribute("listPesanan", listPesanan);
            }
        }

        // Set View
        setView("/pesanan/index", request, response);
    }

    private void actionHistory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String email = (String) request.getSession().getAttribute("email");
        if (email != null) {
            User user = (User) User.getByEmail(email);
            if (user != null) {
                ArrayList<Pesanan> historyPesanan = Pesanan.getInstance().getAllHistory(user.id);
                request.setAttribute("historyPesanan", historyPesanan);
            }
        }

        // Set View
        setView("/pesanan/history", request, response);
    }

    private void actionConfirm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String email = (String) request.getSession().getAttribute("email");
        if (email != null) {
            User user = (User) User.getByEmail(email);
            if (user != null && request.getParameter("pesananId") != null) {
                int pesananId = Integer.parseInt(request.getParameter("pesananId"));
                Pesanan pesanan = Pesanan.getInstance().get(pesananId);
                if (pesanan.user_id == user.id) {
                    pesanan.status = Pesanan.STATUS_CONFIRM_PAY;
                    if(pesanan.update()) {
                        sendEmailConfirm(pesanan);
                    }
                }
            }
        }

        actionIndex(request, response);
    }

    private void actionArrived(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = (String) request.getSession().getAttribute("email");
        if (email != null) {
            User user = (User) User.getByEmail(email);
            if (user != null && request.getParameter("pesananId") != null) {
                int pesananId = Integer.parseInt(request.getParameter("pesananId"));
                Pesanan pesanan = Pesanan.getInstance().get(pesananId);
                if (pesanan.user_id == user.id) {
                    pesanan.status = Pesanan.STATUS_ARRIVED;
                    pesanan.update();
                }
            }
        }
        actionIndex(request, response);

    }

    private void actionCetakNota(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("id") != null) {
            Profil profil = Profil.getCurrentProfil();
            Pesanan pesanan = Pesanan.getInstance().get(Integer.parseInt(request.getParameter("id")));
            response.setContentType("application/pdf");
            //response.setHeader("Content-Disposition", "attachment; filename=\"nota_pesanan" + pesanan.id + ".pdf\"");
            try {
                Document document = new Document();
                PdfWriter.getInstance(document, response.getOutputStream());
                                
                // Membuat dokumen nota
                document.open();
                document.addTitle("Nota Pesanan Kue | www.kueku.com");

                document.add(new Paragraph("Nota Pembelian", new Font(Font.FontFamily.COURIER, 18)));
                document.add(new Paragraph("\n"));

                document.add(new Paragraph("Nama Pemesan : " + User.getInstance().get(pesanan.user_id).nama_lengkap));
                document.add(new Paragraph("No Order : " + pesanan.id));
                document.add(new Paragraph("Waktu Order : " + pesanan.tanggal));
                if (pesanan.kirim != 0) {
                    document.add(new Paragraph("Alamat Pengiriman : " + pesanan.alamat_kirim));
                } else {
                    document.add(new Paragraph("Alamat Pengiriman : -"));
                }
                document.add(new Paragraph("\n"));
                
                PdfPTable table = new PdfPTable(4);                
                table.addCell("Barang");
                table.addCell("Jumlah");
                table.addCell("Harga Satuan");
                table.addCell("Harga Total");
                
                int total = 0;
                for (PesananItem pi : pesanan.getPesananItems()) {
                    Barang barang = Barang.get(pi.barang_id);
                    int jumlah = pi.jumlah;
                    int satuan = pi.harga_satuan;
                    int subtotal = jumlah * satuan;
                    total += subtotal;
                    
                    table.addCell(barang.nama);
                    table.addCell(Integer.toString(jumlah));
                    table.addCell("Rp " + Integer.toString(satuan) + ",00");                    
                    table.addCell("Rp " + Integer.toString(subtotal));
                }
                PdfPCell cell = new PdfPCell(new Paragraph("Sub Total"));
		cell.setColspan(3);
		table.addCell(cell);
                table.addCell("Rp " + Integer.toString(total) + ",00");
                
                cell = new PdfPCell(new Paragraph("Potongan Harga " + pesanan.diskon + "%"));
		cell.setColspan(3);
		table.addCell(cell);
                table.addCell("Rp " + Integer.toString(pesanan.diskon * total / 100) + ",00");
                
                cell = new PdfPCell(new Paragraph("Total"));
		cell.setColspan(3);
		table.addCell(cell);
                table.addCell("Rp " + Integer.toString((100 - pesanan.diskon) * total / 100) + ",00");
                
                document.add(table);
                document.add(new Paragraph("\n"));     

                document.add(new Paragraph("Pembayaran telah diperiksa dan dinyatakan :"));
                document.add(new Paragraph("SUDAH DIBAYAR", new Font(Font.FontFamily.COURIER, 15)));
                document.add(new Paragraph("\n"));

                document.add(new Paragraph("Terima kasih telah melakukan pemesanan di " + profil.nama_toko));
                document.add(new Paragraph("Semoga pelayanan kami memuaskan anda :)"));

                document.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Mengirim email ke pegawai karena pelanggan telah melakukan konfirmasi pembayaran
     * @param pesanan 
     */
    private void sendEmailConfirm(Pesanan pesanan) {
        StringBuilder subject = new StringBuilder();
        StringBuilder message = new StringBuilder();
        User user = pesanan.getUser();
        
        subject.append("Konfirmasi Pembayaran Pesanan ID ").append(pesanan.id);
        message.append("Kepada seluruh Pegawai,\n\n");
        message.append("Pelanggan ").append(user.nama_lengkap).append(" telah melakukan konfirmasi pembayaran pesanan ID ").append(pesanan.id).append(".\n");
        message.append("Segera buka sistem untuk melakukan verifikasi.");
        
        // Kirim email
        MailServer.sendEmail(User.getInstance().getAllEmailPegawai(), subject.toString(), message.toString());
    }
}
